<template>
  <div class="add-role">
    <header class="add-header">
      <div class="left">
        <span class="arrow" @click="$router.back()"><i class="el-icon-arrow-left" />返回</span>
        <span>|</span>
        <span>{{ id? '编辑角色':'添加角色' }}</span>
      </div>
      <div class="right">
        黑马程序员
      </div>
    </header>
    <main class="add-main">
      <div class="step-container">
        <el-steps direction="vertical" :active="active" finish-status="success">
          <el-step title="角色信息" />
          <el-step title="权限信息" />
          <el-step title="检查并完成" />
        </el-steps>
      </div>
      <div v-show="active === 1" class="form-container">
        <div class="title">角色信息</div>
        <div class="form">
          <el-form ref="ruleForm" :model="ruleForm" :rules="rules" label-width="100px" class="demo-ruleForm">
            <el-form-item label="角色名称" prop="roleName">
              <el-input v-model="ruleForm.roleName" style="width: 550px;" />
            </el-form-item>
            <el-form-item label="描述" prop="remark">
              <el-input v-model="ruleForm.remark" style="width: 550px;" type="textarea" />
            </el-form-item>
          </el-form>
        </div>
      </div>
      <div v-show="active === 2" class="form-container">
        <div class="title">权限配置</div>
        <div class="form">
          <div class="tree-wrapper">
            <div v-for="item in getList" :key="item.id" class="tree-item">
              <div class="tree-title">{{ item.title }}</div>
              <el-tree
                ref="tree"
                :data="item.children"
                show-checkbox
                node-key="id"
                :props="defaultProps"
                default-expand-all
                :check-strictly="true"
                :highlight-current="true"
                :default-checked-keys="perms"
              />
            </div>
          </div>
        </div>
      </div>
      <div v-show="active === 3" class="form-container">
        <div class="title">检查并完成</div>
        <div class="form">
          <div>角色名称：{{ ruleForm.roleName }}</div>
          <div>角色描述{{ ruleForm.remark }}</div>
          <div class="form">
            <div class="tree-wrapper">
              <div v-for="item in setList" :key="item.id" class="tree-item">
                <div class="tree-title">{{ item.title }}</div>
                <el-tree
                  ref="refTree"
                  :data="item.children"
                  show-checkbox
                  node-key="id"
                  :props="{disabled:()=>true,label: 'title'}"
                  default-expand-all
                  :check-strictly="true"
                  :highlight-current="true"
                  :default-checked-keys="ruleForm.perms"
                />
              </div>
            </div>
          </div>
        </div>
      </div>
    </main>
    <footer class="add-footer">
      <div class="btn-container">
        <el-button v-if="active>1" @click="last">上一步</el-button>
        <el-button v-if="active<3" type="primary" @click="next">下一步</el-button>
        <el-button v-else type="primary" @click="submit">{{ id? '编辑':'添加' }}</el-button>
      </div>
    </footer>
  </div>
</template>

<script>
import { getAllPermissionAPI, addRoleAPI, getRoleDetailAPI, editRoleAPI } from '@/api/roleUser'
export default {
  data() {
    return {
      // 当前步骤
      active: 1,
      getList: [],
      setList: [],
      perms: [],
      ruleForm: {
        roleName: '',
        remark: '',
        perms: []
      },
      defaultProps: {
        children: 'children',
        label: 'title'
      },
      rules: {
        roleName: [
          { required: true, message: '请输入角色名称', trigger: 'blur' }
        ],
        remark: [
          { required: true, message: '请输入角色描述', trigger: 'blur' }
        ]
      }
    }
  },
  computed: {
    id() {
      return this.$route.query.id
    }
  },
  async mounted() {
    // 渲染页面时，获取所有权限
    await this.getAllPermission()
    // 有id则获取编辑角色信息
    if (this.id) {
      this.getRoleDetail()
    }
  },
  methods: {
    // 获取编辑角色信息
    async getRoleDetail() {
      const res = await getRoleDetailAPI(this.id)
      const { roleName, remark, perms, roleId } = res.data
      this.ruleForm = { perms, roleName, remark, roleId }
      this.perms = perms
      await this.$refs.tree.forEach((item, index) => {
        item.setCheckedKeys(this.perms[index])
      })
    },
    // 下一步，active+1
    async next() {
      // 如果当前是第三步，则return
      if (this.active === 3) {
        return
      }
      // 如果当前是第一步，则校验表单
      if (this.active === 1) {
        this.$refs.ruleForm.validate(valid => {
          if (valid) {
            this.active++
          }
        })
        // 如果当前是第二步，则校验权限
      } else if (this.active === 2) {
        // 获取树形权限
        this.ruleForm.perms = []
        // 获取树形权限的id
        this.$refs.tree.forEach(item => {
          const keys = item.getCheckedKeys()
          this.ruleForm.perms.push(keys)
        })

        // 如果没有选择权限，则提示用户选择权限
        if (this.ruleForm.perms.flat().length === 0) {
          this.$message.error('请选择权限')
          return
        } else {
          this.active++
          // 如果有权限，则将权限赋值给树形权限,异步
          const tree = await this.$refs.refTree
          if (tree) {
            // 如果有权限，则将权限赋值给树形权限,异步
            await tree.forEach((item, index) => {
              item.setCheckedKeys(this.ruleForm.perms[index])
            })
          }
        }
      }
    },
    // 上一步，active-1
    last() {
      if (this.active-- === 1) return
    },
    // 封装获取所有权限
    async getAllPermission() {
      const res = await getAllPermissionAPI()
      this.getList = res.data
      this.setList = JSON.parse(JSON.stringify(res.data))
    },
    // 提交
    async submit() {
      if (this.id) {
        const { perms, roleName, remark, roleId } = this.ruleForm
        await editRoleAPI({ perms, roleName, remark, roleId })
        this.$message.success('编辑成功')
      } else {
        await addRoleAPI(this.ruleForm)
        this.$message.success('添加成功')
      }
      this.$router.back()
    }

  }

}
</script>
<style scoped lang="scss">
.add-role {
  background-color: #f4f6f8;
  height: 100vh;

  .add-header {
    display: flex;
    justify-content: space-between;
    padding: 0 20px;
    height: 64px;
    line-height: 64px;
    font-size: 16px;
    font-weight: bold;
    background-color: #fff;

    .left {
      span {
        margin-right: 4px;
      }

      .arrow {
        cursor: pointer;
      }
    }

    .right {
      text-align: right;
    }
  }

  .add-main {
    position: fixed;
    top: 64px;
    bottom: 88px;
    width: 100%;
    overflow-y: auto;
    background: #f4f6f8;
    padding: 20px 230px;
    display: flex;
    .step-container {
      height: 400px;
      width: 200px;
    }
    .form-container {
      flex:1;
      background-color: #fff;
      overflow-y: auto;
      .title {
        height: 60px;
        line-height: 60px;
        padding-left: 20px;
      }
      .form {
        margin-bottom: 20px;
        padding: 20px 65px 24px;
        .el-form {
          display: flex;
          flex-wrap: wrap;
        }
        .info{
          font-size:14px;
          color:#666;
          .form-item{
            margin-bottom:20px;
          }
        }
      }
      .form-box{
        width: 600px;
        display: flex;
        flex-direction: column;
      }
    }
  }

  .add-footer {
    position: fixed;
    bottom: 0;
    width: 100%;
    padding: 24px 50px;
    color: #000000d9;
    font-size: 14px;
    background: #fff;
    text-align: center;
    z-index: 10001;
  }
  .tree-wrapper {
      display: flex;
      justify-content: space-evenly;

      .tree-item {
        flex: 1;
        padding: 0px 4px;
        text-align: center;
        .tree-title {
          background: #f5f7fa;
          text-align: center;
          padding: 10px 0;
          margin-bottom: 12px;
        }
      }
    }
}
</style>

